package com.angel.architecture.initializer.injector;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.angel.architecture.initializer.modules.AbstractModuleDescriptor;
import com.angel.architecture.services.locator.ApplicationRegistryReader;
import com.angel.common.helpers.CollectionHelper;
import com.angel.common.helpers.ReflectionHelper;

/**
 *
 * @author William
 *
 */
public class DependecyInjector{

	private static final Logger LOGGER = Logger.getLogger(DependecyInjector.class);


	public static void autoInject(Object object) {
		if (object == null) {
			return;
		}
		Class<?> clase = object.getClass();
		List<Injector> allInjectors = ApplicationRegistryReader.getInstance().getAllInjectors();
		List<Field> fields = CollectionHelper.convertGenericTo(ReflectionHelper.getFieldsDeclaredFor(clase));
		for (Field field: fields) {
			for (Injector injector : allInjectors){
				LOGGER.debug("Injecting field [" + field + "] at object [" + object + "]");
				try {

					if(ReflectionHelper.getFieldValue(object, field) == null){
						injector.inject(field, object);
					}
				} catch (IllegalArgumentException e) {
					// TODO Change exception.
					e.printStackTrace();
				}
			}
		}
	}

	public void autoInject(Object object, AbstractModuleDescriptor moduleDescriptor) {
		LOGGER.info("Injecting with data generator dependency injector.");
		if (object == null) {
			return;
		}
		List<Injector> injectors = new ArrayList<Injector>();
		moduleDescriptor.registerInjectors(injectors);
		Class<?> clase = object.getClass();
		List<Field> fields = CollectionHelper.convertGenericTo(ReflectionHelper.getFieldsDeclaredFor(clase));
		for (Field field: fields) {
			for (Injector injector : injectors){
				LOGGER.debug("Injecting field [" + field + "] at object [" + object + "]");
				try {
					if(ReflectionHelper.getFieldValue(object, field) == null){
						injector.inject(field, object);
					}
				} catch (IllegalArgumentException e) {
					// TODO Change exception.
					e.printStackTrace();
				}
			}
		}
	}
}
